import React, { useCallback, useState, useEffect } from "react";
import { Form } from "antd";

import config from "src/commons/config-hoc";
import { ModalContent } from "src/library/components";
import { useGet, usePost, usePut } from "src/commons/ajax";
import { FormElement } from "src/library/components";

export default config({
    modal: {
        title: (props) => (props.isEdit ? "修改" : "添加"),
    },
})((props) => {
    const { isEdit, id, onOk, formdata, passid } = props;
    console.log(isEdit, "isEdit");
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [form] = Form.useForm();
    const [saving, saveUser] = usePost("/admin/specsValue/add", {
        successTip: "添加成功！",
    });
    const [updating, updateUser] = usePost("/admin/specsValue/update", {
        successTip: "编辑成功！",
    });

    async function fetchData() {
        if (loading) return;
        console.log(id);

        // const res = await fetchUser(id);

        setData(formdata || {});
        form.setFieldsValue(formdata || {});
    }

    async function handleSubmit(values) {
        if (saving || updating) return;

        const ajaxMethod = isEdit ? updateUser : saveUser;
        let data = Object.assign(values, {
          specs_id: passid
        })
        await ajaxMethod(data);

        onOk && onOk();
    }

    useEffect(() => {
        if (isEdit) fetchData();
    }, []);

    const modalLoading = loading || saving || updating;

    const formProps = {
        labelWidth: 100,
    };

    return (
        <ModalContent
            loading={modalLoading}
            okText="保存"
            cancelText="重置"
            onOk={() => form.submit()}
            onCancel={() => form.resetFields()}
        >
            <Form form={form} onFinish={handleSubmit} initialValues={data}>
                {isEdit ? (
                    <FormElement {...formProps} type="hidden" name="id" />
                ) : null}

                <FormElement
                    {...formProps}
                    label="规格属性名称"
                    name="name"
                    required
                    noSpace
                />
                {isEdit ? (
                    <FormElement
                        {...formProps}
                        label="显示隐藏"
                        type="select"
                        name="status"
                        options={[
                            { value: 1, label: "显示" },
                            { value: 0, label: "隐藏" },
                        ]}
                    />
                ) : null}
            </Form>
        </ModalContent>
    );
});
